<?php

use console\db\channels\TransferTableMigration;
use yii\db\Query;

/**
 * 用户签到信息转移
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300030_000040_t_signin_history_one extends TransferTableMigration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_signin_history}}';

    /**
     * 是否先清理本地数据表
     */
    public $beforeTruncateTargetTable = false;

    /**
     * @inheritdoc
     */
    public function buildQuery() {
        return (new Query())->from('{{%' . $this->sourceTable . '}}')->select('user_id')
        ->groupBy('user_id')
        ->having('count(*)=1');
    }

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $this->delete($this->tableName, ['days' => 1]);
        parent::safeUp();
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->delete($this->tableName, ['days' => 1]);
    }

    public function validateTransfer(&$data) {
        $data = (new Query())->from('{{%' . $this->sourceTable . '}}')
        ->where([
            'user_id' => $data['user_id']
        ])
        ->one();
        return true;
    }

    /**
     * @inheritdoc
     */
    public function getTransferOptions() {
        return [
            'table' => [
                'user_signin_history' => 'user_signin_log',
            ],
            'columns' => [
                'user_id',
                'days' => function() {
                    return 1;
                },
                'first_date' => function($data) {
                    return date('Y-m-d', $data['created_at']);
                },
                'last_date' => function($data) {
                    return date('Y-m-d', $data['created_at']);
                },
                'sign_days' => function() {
                    return 1;
                },
                'history' => function() {
                    return 1;
                },
                'created_at',
                'updated_at' => 'created_at',
            ],
        ];
    }

}
